// pages/songDetail/songDetail.js
import PubSub from  'pubsub-js'
var util = require("../../utils/util.js")
// 获取全局实例
const appInstance = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPlay:false,
    ids:'',
    musicInfo:'',
    musicUrlId:'',
  },
  async getSongUrl(){
    let res = await util.publicRequest("http://localhost:3000/song/url",{
      id:this.data.musicUrlId
    })
    return res.data[0]
  },
  handleMusicPlay(){
    let play = !this.data.isPlay
    this.changePlayState(play)
    
    if(play){
      // 创建控制音乐播放的实例对象
      this.getSongUrl().then(item=>{
        this.bgAudioManager.src = item.url
      })
      this.bgAudioManager.title = this.data.musicInfo.name
    }else{
      this.bgAudioManager.pause()
    }
  },
  async getSongDetail(){
    let res = await util.publicRequest("http://localhost:3000/song/detail",{
      ids:this.data.ids
    })
    this.setData({
      musicInfo:res.songs[0],
      musicUrlId:res.privileges[0].id
    })
    wx.setNavigationBarTitle({
      title: res.songs[0].name
    })

  },
  changePlayState(isPlay){
    this.setData({
      isPlay
    })
    appInstance.globalData.isPlay = isPlay
  },
  // 点击切歌回调
  handleSwitch(event){
    // 获取切歌的类型
    let type = event.currentTarget.id
    PubSub.subscribe("musicID",(msg,data)=>{
      console.log(msg,data)
      PubSub.unsubscribe("musicID")
    })
    PubSub.publish('switchType',type)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取路由传递的参数
    let musicId = options.musicId
    this.setData({
      ids:musicId
    })
    this.getSongDetail()

    this.bgAudioManager = wx.getBackgroundAudioManager()
  //  判断当前页面音乐是否在播放
  if(appInstance.globalData.isPlay && appInstance.globalData.musicId==musicId){
    // 如果是播放的歌曲ID相同，则修改为true
    this.setData({
      isPlay:true
    })

  }
   
    this.bgAudioManager.onPlay(()=>{
      this.changePlayState(true)
      appInstance.globalData.musicId = this.data.ids
    })
    this.bgAudioManager.onPause(()=>{
      this.changePlayState(false)
    })
    this.bgAudioManager.onStop(()=>{
      this.changePlayState(false)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})